<template>
    <div :style="carStyle">
        <div v-if="!showContent" class="defaultText">请在右侧配置数据</div>
        <template v-else>
            <div class="lineTitle" v-if="obj.isShowTitle" :style="titleStyle">{{ obj.title }}</div>
        </template>
        <div class="chart" ref="constat" :style="canvasStyle" @click="gotoUrl(obj)"></div>
    </div>
</template>

<script>
// 新的仪表盘更简单
import * as echarts from 'echarts';
// import { oneLoad, boardOneLoad } from '@/api/share'
// import { title } from '@/settings';

export default {
    Name: "Gauge",
    components: {
        echarts
    },
    props: {
        obj: Object,
        discount: Number,
        isReload: {
            type: Boolean,
            default: false
        },
        isEdit: {
            type: Boolean,
            default: false,
        },
        gotoUrl: Function,
        getTableValue: Function,
    },
    data() {
        return {
            showContent: true,
            carStyle: {},
            titleStyle: {},
            canvasStyle: {
                width: "100%",
                height: "100%"
            },
            chart: undefined,
            // 用于比对数据是否修改
            dataStr: "",
            timer: null,
            dataValue: 0,
            filterForm: {},
        }
    },
    mounted() {
        this.setStyle();

        this.$nextTick(function () {
            this.reloadInfo();
        })

        this.dataStr = JSON.stringify(this.obj.tableData);

        // 页面变化调整尺寸
        var self = this;
        window.addEventListener('resize', function () {
            if (self.chart) {
                self.chart.resize();
            }
        }, true);
    },
    beforeDestroy() {
        if (!this.chart) {
            return
        }
        this.chart.dispose()
        this.chart = null
        clearInterval(this.timer)
    },
    methods: {
        // 除样式外其他数据更改调用刷新
        reloadInfo() {
            if (this.chart) {
                this.chart.dispose()
            }
            var constat = this.$refs.constat;
            this.chart = echarts.init(constat);

            var timeSize = 60;
            if (this.obj.tableData.reloadTime) {
                timeSize = this.obj.tableData.reloadTime;
            }

            if (this.obj.tableData.type == 1) {
                // 刷新时间兼容处理
                if (timeSize < 60) {
                    timeSize = 60;
                }
            }

            clearInterval(this.timer);
            this.getFirstData();

            if (this.isReload) {
                this.timer = setInterval(() => {
                    this.getLineData();
                }, timeSize * 1000);
            }
        },
        setStyle() {
            var style = this.obj.style;

            var backgroundColor = "";
            var backgroundImage = "";
            // 背景颜色
            if (style.backgroundImage.length) {
                backgroundImage = `url(${style.backgroundImage}`;
            } else if (style.backgroundColor.length > 0) {
                backgroundColor = style.backgroundColor;
            } else {
                backgroundColor = "#04142b";
            }

            var boxShadow = "";
            if (style.boxShadow) {
                boxShadow = `${style.boxShadow.h}px ${style.boxShadow.v}px ${style.boxShadow.blur}px ${style.boxShadow.spreed}px ${style.boxShadow.color}`
            }

            this.carStyle = {
                boxShadow,
                width: "100%",
                height: "100%",
                display: "flex",
                backgroundSize: "100% 100%",
                borderStyle: "solid",
                backgroundImage,
                backgroundColor,
                color: style.color,
                fontSize: style.fontSize + "px",
                justifyContent: style.justifyContent,
                alignItems: style.alignItems,
                borderColor: style.borderColor,
                borderWidth: style.borderWidth + "px",
                borderRadius: style.borderRadius + "px",
                fontWeight: style.fontWeight,
                fontStyle: style.fontStyle,
            }

            // #region 新的背景颜色

            if (this.obj.style.bgcolorType == "image") {
                this.carStyle.backgroundImage = backgroundImage;
            } else if (this.obj.style.bgcolorType == "gradient") {
                if (this.obj.style.gradient.isRadial) {
                    this.carStyle.backgroundImage = `radial-gradient(${this.obj.style.gradient.colorStart}, ${this.obj.style.gradient.colorEnd})`;
                } else {
                    this.carStyle.backgroundImage = `linear-gradient(${this.obj.style.gradient.fontAngle}deg, ${this.obj.style.gradient.colorStart}, ${this.obj.style.gradient.colorEnd})`;
                }
            } else {
                this.carStyle.backgroundColor = backgroundColor;
            }

            // #endregion

            this.titleStyle = {
                justifyContent: style.justifyContent,
                alignItems: style.alignItems,
            }

            // 标题隐藏显示
            var isShowTitle = this.obj.isShowTitle ? true : false;
            var echarHeight = style.height;
            var echarMarginTop = 0;
            if (isShowTitle) {
                echarHeight = style.height - style.fontSize - style.borderWidth * 2;
                echarMarginTop = style.fontSize + "px";
            }

            this.canvasStyle = {
                marginTop: echarMarginTop,
                width: "100%",
                height: echarHeight + "px",
            }

            if (this.chart) {
                this.chart.resize({
                    width: style.width,
                    height: echarHeight,
                });
            }
        },
        setOptions() {
            var value = this.dataValue;
            // this.chart.clear()

            var maxValue = this.obj.tableData.maxNumber;
            var minNumber = this.obj.tableData.minNumber;

            // var color = "#333333";
            // if (this.obj.tableData.color) {
            //     color = this.obj.tableData.color;
            // }

            var textStyle = {
                fontSize: '52px', //文本字号,
                color: "#fff",
                fontWeight: '',
                fontStyle: ''
            }
            if (this.obj.tableData.fontSize) {
                textStyle.fontSize = this.obj.tableData.fontSize + "px";
            }
            if (this.obj.tableData.fontColor) {
                textStyle.color = this.obj.tableData.fontColor;
            }
            if (this.obj.tableData.fontWeight) {
                textStyle.fontWeight = this.obj.tableData.fontWeight;
            }
            if (this.obj.tableData.fontStyle) {
                textStyle.fontStyle = this.obj.tableData.fontStyle;
            }


            if (this.obj.tableData.styleTemplate == 1) {
                var color = new echarts.graphic.LinearGradient(0, 0, 1, 0, [{
                    offset: 0,
                    color: "#00B0FF", // 0% 处的颜色
                },
                {
                    offset: 0.2,
                    color: "#0071CB", // 100% 处的颜色
                },
                {
                    offset: 1,
                    color: "#08BBED", // 100% 处的颜色
                },
                ]);

                var bgColor = new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                    offset: 0,
                    color: "#00B0FF00", // 0% 处的颜色
                },
                {
                    offset: 1,
                    color: "#0073FF33", // 100% 处的颜色
                },
                ]);

                var colorSet = [
                    [1, color]
                ];

                var option = {
                    // backgroundColor: "#0E1327",
                    tooltip: {
                        formatter: "{a} <br/>{b} : {c}%",
                    },
                    series: [{
                        radius: "90%",
                        splitNumber: 10,
                        name: "",
                        z: 10,
                        type: "gauge",
                        detail: {
                            show: false,
                        },
                        data: [{
                            value: value,
                        },],
                        axisTick: {
                            show: false,
                        },
                        splitLine: {
                            show: false,
                        },
                        max: maxValue,
                        axisLine: {
                            lineStyle: {
                                width: 3,
                                color: colorSet,
                            },
                        },
                        axisLabel: {
                            show: false,
                        },
                        pointer: {
                            // 表盘上的指针
                            show: true,
                            length: "70%",
                        },
                        itemStyle: {
                            // 表盘指针的颜色
                            color: "#08BBED",
                        },
                    },
                    {
                        name: "白色圈刻度",
                        type: "gauge",
                        radius: "97%",
                        startAngle: 225, //刻度起始
                        endAngle: -45, //刻度结束
                        min: minNumber,
                        max: maxValue,
                        splitNumber: 10,
                        z: 8,
                        axisTick: {
                            show: false,
                        },
                        splitLine: {
                            length: 16, //刻度节点线长度
                            lineStyle: {
                                width: 2,
                                color: "#018DFF",
                            }, //刻度节点线
                        },
                        //度节点文字颜色
                        axisLabel: textStyle,
                        pointer: {
                            show: false,
                        },
                        axisLine: {
                            lineStyle: {
                                opacity: 0,
                            },
                        },
                        detail: {
                            show: false,
                        },
                    },
                    {
                        name: "内外圆",
                        type: "pie",
                        radius: ["28%", "46%"],
                        z: 5,
                        itemStyle: {
                            color: "rgba(0,49,154,0.1)",
                        },
                        hoverAnimation: false,
                        label: {
                            show: false,
                        },
                        tooltip: {
                            show: false,
                        },
                        data: [100],
                        animationType: "scale",
                    },
                    {
                        //内圆
                        name: "内外圆-渐变",
                        type: "pie",
                        radius: "28%",
                        z: 0,
                        itemStyle: {
                            normal: {
                                color: new echarts.graphic.RadialGradient(
                                    0.5,
                                    0.5,
                                    0.7,
                                    [{
                                        offset: 0,
                                        color: "#4978EC",
                                    },
                                    {
                                        offset: 0.32,
                                        color: "#1E2B57",
                                    },
                                    {
                                        offset: 0.4,
                                        color: "#141F3D",
                                    },
                                    {
                                        offset: 1,
                                        color: "#141F3D",
                                    },
                                    ],
                                    false
                                ),
                                label: {
                                    show: false,
                                },
                                labelLine: {
                                    show: false,
                                },
                            },
                        },
                        hoverAnimation: false,
                        label: {
                            show: false,
                        },
                        tooltip: {
                            show: false,
                        },
                        data: [100],
                        animationType: "scale",
                    },
                    {
                        name: "小圆形",
                        type: "pie",
                        hoverAnimation: false,
                        legendHoverLink: false,
                        tooltip: {
                            show: false,
                        },
                        radius: ["8%", "9%"],
                        z: 10,
                        label: {
                            normal: {
                                show: false,
                                position: "center",
                            },
                            emphasis: {
                                show: false,
                            },
                        },
                        labelLine: {
                            normal: {
                                show: false,
                            },
                        },
                        data: [{
                            value: 100,
                            name: "2",
                            itemStyle: {
                                normal: {
                                    color: colorSet,
                                },
                            },
                        },],
                    },
                    {
                        name: "小圆形",
                        type: "pie",
                        hoverAnimation: false,
                        legendHoverLink: false,
                        radius: ["0%", "5%"],
                        tooltip: {
                            show: false,
                        },
                        z: 10,
                        label: {
                            normal: {
                                show: false,
                                position: "center",
                            },
                            emphasis: {
                                show: false,
                            },
                        },
                        labelLine: {
                            normal: {
                                show: false,
                            },
                        },
                        data: [{
                            value: 100,
                            name: "2",
                            itemStyle: {
                                normal: {
                                    color: "#4672e0",
                                },
                            },
                        },],
                    },
                    {
                        name: "小圆形",
                        type: "pie",
                        hoverAnimation: false,
                        legendHoverLink: false,
                        radius: ["5%", "6%"],
                        tooltip: {
                            show: false,
                        },
                        z: 10,
                        label: {
                            normal: {
                                show: false,
                                position: "center",
                            },
                            emphasis: {
                                show: false,
                            },
                        },
                        labelLine: {
                            normal: {
                                show: false,
                            },
                        },
                        data: [{
                            value: 100,
                            name: "2",
                            itemStyle: {
                                normal: {
                                    color: "#08BBED",
                                },
                            },
                        },],
                    },
                    {
                        name: "小圆形",
                        type: "pie",
                        hoverAnimation: false,
                        legendHoverLink: false,
                        tooltip: {
                            show: false,
                        },
                        radius: ["6%", "8%"],
                        z: 10,
                        label: {
                            normal: {
                                show: false,
                                position: "center",
                            },
                            emphasis: {
                                show: false,
                            },
                        },
                        labelLine: {
                            normal: {
                                show: false,
                            },
                        },
                        data: [{
                            value: 0,
                            name: "1",
                            itemStyle: {
                                normal: {
                                    color: "red",
                                },
                            },
                        },
                        {
                            value: 100,
                            name: "2",
                            itemStyle: {
                                normal: {
                                    color: "#4672e0",
                                },
                            },
                        },
                        ],
                    },
                    ]
                };
            } else if (this.obj.tableData.styleTemplate == 2) {
                option = {
                    series: [{
                        type: 'gauge',
                        radius: '90%',
                        min: minNumber,
                        max: maxValue,
                        progress: {
                            show: true,
                            width: 18,
                        },
                        axisLine: {
                            lineStyle: {
                                width: 18
                            }
                        },
                        axisTick: {
                            show: false
                        },
                        splitLine: {
                            length: 12,
                            lineStyle: {
                                width: 2,
                                color: '#999'
                            }
                        },
                        axisLabel: {
                            distance: 20,
                            color: '#999',
                            fontSize: 16
                        },
                        anchor: {
                            show: true,
                            showAbove: true,
                            size: 22,
                            itemStyle: {
                                borderWidth: 10
                            }
                        },
                        title: {
                            show: false
                        },
                        detail: {
                            formatter: function (value2) {
                                return value;
                            },
                            valueAnimation: true,
                            fontSize: textStyle.fontSize,
                            color: textStyle.color,
                            fontWeight: textStyle.fontWeight,
                            offsetCenter: [0, '70%']
                        },
                        data: [{
                            value: value
                        }]
                    }]
                };
            } else if (this.obj.tableData.styleTemplate == 3) {
                // 获取位置信息
                var pos_info = ['50%', '50%'];

                // 圆环颜色配置
                var color_cfg = [
                    [
                        { offset: 0, color: 'rgba(50, 197, 255, 1)', },
                        { offset: 0.5, color: 'rgba(254, 219, 101, 1)', },
                        { offset: 1, color: 'rgba(250, 100, 0, 1)', }
                    ]
                ];

                // 拼接图表参数
                var series = [
                    {
                        name: '最外层',
                        type: 'gauge',
                        center: pos_info,
                        radius: '90%',
                        startAngle: 150,
                        endAngle: -209.999,
                        axisLine: {
                            show: true,
                            lineStyle: { width: 2, color: [[1, "rgba(25, 235, 255,1)"]] },
                        },
                        axisLabel: { show: false },
                        axisTick: { show: false },
                        splitLine: { show: false },
                        detail: { show: false },
                        pointer: { show: false }
                    },
                    {
                        name: '内层渐变区',
                        type: 'gauge',
                        radius: '45%',
                        splitNumber: 10,            // 刻度数量
                        center: pos_info,
                        startAngle: 150,
                        endAngle: -209.999,
                        axisLine: {
                            lineStyle: {
                                color: [[
                                    1, {
                                        type: 'radial',
                                        colorStops: [
                                            { offset: 0.72, color: '#0320462e' },
                                            { offset: 0.84, color: '#08698961' },
                                            { offset: 0.98, color: '#0FAFCBa6' },
                                            { offset: 1, color: '#0EA4C1f0' }
                                        ]
                                    }]
                                ],
                                width: 1000
                            }
                        },
                        splitLine: { show: false },   // 分隔线
                        axisTick: { show: false },   // 刻度线
                        axisLabel: { show: false },   // 刻度标签
                        pointer: { show: false },   // 仪表盘指针
                        detail: { show: false }
                    }, {
                        name: "中间层",
                        type: 'gauge',
                        center: pos_info,
                        radius: '82%',
                        min: minNumber,                 // 最小刻度
                        max: maxValue,                 // 最大刻度
                        splitNumber: 10,                       // 刻度数量
                        startAngle: 245,
                        endAngle: -65,
                        data: [{ value: value }],
                        axisLine: {
                            show: true,
                            lineStyle: {
                                width: 15,
                                color: [
                                    [
                                        value / maxValue,
                                        new echarts.graphic.LinearGradient(0, 1, 1, 0, color_cfg[0]),
                                    ],
                                    [1, 'rgba(50, 197, 255,.1)']
                                ],
                            },
                        },
                        axisLabel: { show: true, color: '#fff', distance: 42, textStyle: { fontSize: 10 } },
                        axisTick: { show: true, length: -5, distance: -15, lineStyle: { color: 'rgba(25, 235, 255, 1)', } },
                        splitLine: { show: true, length: -10, distance: -15, lineStyle: { width: 1, color: 'rgba(25, 235, 255, 1)', }, },
                        detail: {
                            offsetCenter: [0, '-5%'],
                            textStyle: { fontSize: textStyle.fontSize, color: textStyle.color, fontWeight: textStyle.fontWeight, },
                            formatter: [this.obj.title, '{name|' + this.dataValue + '}'].join('\n'),
                            rich: { name: { fontSize: textStyle.fontSize, lineHeight: 18, color: textStyle.color, fontWeight: textStyle.fontWeight, }, },
                        },
                        title: { color: '#fff', },
                        pointer: { show: false }
                    }];

                option = {
                    series: series,
                };
            } else {
                var pointerColor = new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    {
                        offset: 0,
                        color: '#2EE5E3',
                    },
                    {
                        offset: 1,
                        color: '#385CF7',
                    },
                ]);
                var color = new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                    {
                        offset: 0,
                        color: '#2EE5E3',
                    },
                    {
                        offset: 1,
                        color: '#385CF7',
                    },
                ]);

                option = {
                    series: [
                        {
                            name: '',
                            type: 'gauge',
                            radius: '90%',
                            startAngle: 225,
                            endAngle: -45,
                            min: minNumber,
                            max: maxValue,
                            title: {
                                show: false,
                            },
                            detail: {
                                formatter: function (value2) {
                                    return value;
                                },
                                color: textStyle.color,
                                fontSize: textStyle.fontSize,
                                fontWeight: textStyle.fontWeight,
                                fontStyle: textStyle.fontStyle,
                                show: true,
                                offsetCenter: [0, '80%']
                            },
                            axisLine: {
                                roundCap: true,
                                show: true,
                                lineStyle: {
                                    width: 20,
                                    color: [
                                        [
                                            value / maxValue, color
                                        ],
                                        [
                                            1, 'rgba(225,225,225,0.4)'
                                        ]
                                    ],
                                    // shadowColor: 'rgba(0,138,255,0.35)',
                                    // shadowBlur: 5,
                                },
                            },
                            axisTick: {
                                distance: -20,
                                length: 7,
                                lineStyle: {
                                    color: '#fff',
                                    width: 1,
                                },
                            },
                            axisLabel: {
                                show: false,
                            },
                            pointer: {
                                itemStyle: {
                                    color: pointerColor,
                                },
                                length: '80%',
                                width: '5%',
                            },
                            itemStyle: {
                                color: color,
                                shadowColor: 'rgba(0,138,255,0.45)',
                                shadowBlur: 10,

                                // shadowOffsetX: 2,
                                // shadowOffsetY: 2,
                            },
                            splitLine: {
                                show: true,
                                length: 20,
                                distance: -20,
                                lineStyle: {
                                    color: '#fff',
                                    width: 1,
                                },
                            },
                            data: [
                                {
                                    value: value,
                                },
                            ],
                        },
                    ],
                };
            }

            this.chart.setOption(option);
        },
        getFirstData() {
            if (this.obj.tableData.tableId && this.obj.tableData.itemId) {
                var result = this.getTableValue(this.obj.tableData.tableId, this.obj.tableData.itemId, 1);
                if (result.code == 200) {
                    this.getLineData();
                } else {
                    var self = this;
                    window.setTimeout(function () {
                        self.getFirstData();
                    }, 500);
                }
            }

            // #region 没有配置数据显示默认内容
            if (!this.obj.tableData.tableId) {
                this.showContent = true;
                this.dataValue = 0;
                this.setOptions();
                return false;
            }
            // #endregion

            // #region 参数不完整
            if (!this.obj.tableData.itemId || this.obj.tableData.maxNumber <= 0) {
                this.showContent = false;
                return false;
            }
            // #endregion
        },
        getLineData() {
            var result = this.getTableValue(this.obj.tableData.tableId, this.obj.tableData.itemId, 1);
            if (result.code == 200) {
                var value = result.data;
                this.showContent = true;
                if (this.obj.tableData.decimal >= 0) {
                    value = Number(value).toFixed(this.obj.tableData.decimal);
                }
                this.dataValue = value;
                this.setOptions();
            }
            return false;

            if (this.obj.tableData.tableId && this.obj.tableData.itemId) {
                this.filterForm.tableId = this.obj.tableData.tableId;
                this.filterForm.structureId = this.obj.tableData.itemId;

                if (this.obj.tableData.isOnlie == undefined || this.obj.tableData.type != 1) {
                    oneLoad(this.filterForm).then((res) => {
                        if (res.data.code == 0) {
                            var value = res.data.data;

                            this.showContent = true;
                            if (this.obj.tableData.decimal >= 0) {
                                value = Number(value).toFixed(this.obj.tableData.decimal);
                            }
                            this.dataValue = value;
                            this.setOptions();
                        } else {
                            console.error(res.data.message)
                        }
                    }).catch(() => {
                        clearInterval(this.timer)
                    });
                } else {
                    boardOneLoad(this.filterForm).then((res) => {
                        if (res.data.code == 0) {
                            var value = res.data.data;

                            this.showContent = true;
                            if (this.obj.tableData.decimal >= 0) {
                                value = Number(value).toFixed(this.obj.tableData.decimal);
                            }
                            this.dataValue = value;
                            this.setOptions();
                        } else {
                            console.error(res.data.message)
                        }
                    }).catch(() => {
                        clearInterval(this.timer)
                    });
                }
            }
        },
    },
    watch: {
        obj: {
            handler(newVal, oldVal) {
                this.setStyle();

                // // 数据改变了 动态更新echart
                if (JSON.stringify(this.obj.tableData) != this.dataStr) {
                    this.dataStr = JSON.stringify(this.obj.tableData);

                    this.reloadInfo();
                } else {
                    this.setOptions();
                }
            },
            deep: true,  // 深度监听
        }
    },
}
</script>